import {
  lockSysUser,
  articleLaudSave,
  scenicFavoritesSave,
  scenicFavoritesDel,
  scenicFavoritesList
} from '../api/member';

function datetimeFormat(time, sep = '-') {
  var date = new Date(time);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join(sep) + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function datetime(time, sep = '-') {
  var date = new Date(time);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join(sep)
}

function filterTime(time, sep = '-') {
  var date = new Date(time);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [hour, minute, second].map(formatNumber).join(':')
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 计算距当前时间的时间差
 * 超出三天则显示具体日期
 * @param {Number} date 以毫秒表示的时间戳
 * @param {String} form 具体到时间'time'或者日期'date'
 */
function getDateFromNow(pastDate, form = 'time') {
  let currentDate = new Date().getTime()
  let dateDiff = currentDate - pastDate;
  if (dateDiff <= 0)
    wx.showToast({
      icon: 'none',
      title: '仅支持传入过去时间！',
    })
  const compareDates = [{
      postfix: "秒前",
      limit: 60
    },
    {
      postfix: "分钟前",
      limit: 60
    },
    {
      postfix: "小时前",
      limit: 24
    },
    {
      postfix: "天前",
      limit: 3
    }
  ]
  let rate = 1000;
  for (let i = 0; i < compareDates.length; i++) {
    let e = compareDates[i];
    if (dateDiff < (rate *= e.limit)) {
      return Math.round(dateDiff / (rate / e.limit)) + e.postfix
    }
  }
  switch (form) {
    case 'date':
      return datetime(new Date(pastDate))
    case 'time':
      return datetimeFormat(new Date(pastDate))
    default:
      return datetimeFormat(new Date(pastDate))
  }
}


/**
 * 倍率转换器 转换数字显示倍率
 * @param {Number} Num 需要转换倍率的数字 例如转换 1500m->1.5km 
 * @param {Number} round 保留小数位数
 * @param {Object} rateSymbol {倍率：后缀}
 */
function rateConverter(Num, round = 1, rateSymbol = {
  1e3: "k"
}) {
  let n = Num || 0
  let rateSymbolKeys = Object.keys(rateSymbol).sort((a, b) => b - a)
  for (let i = 0; i < rateSymbolKeys.length; i++) {
    let rate = rateSymbolKeys[i]
    let decimal = (n / rate).toFixed(round)
    if (decimal >= 1) {
      if (!i && decimal >= 100) {
        return '>' + (100).toFixed(round) + rateSymbol[rate]
      }
      return decimal + rateSymbol[rate]
    }
  }
  return n.toFixed(round)
}

/**
* 富文本转义
* @param {obj, obj}
* @return {number}
*/
const escape2Html = (str = "") => {
  var arrEntities = {
    'lt': '<',
    'gt': '>',
    'nbsp': '<span style="width: 0.33em;display: inline-block;"></span>',
    'amp': '&',
    'quot': '"'
  };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });
}


// 创建全局唯一标识符
const getUUID = () => {
  var d = new Date().getTime()
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid
}

const getUrlParameter = (name) => {
  var url = window.location.href
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = url.slice(url.indexOf('?') + 1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}

const thumbnail = (url, w, h) => {
  if (url.indexOf('?x-oss-') != -1) {
    url = url.substring(0, url.indexOf('?x-oss-'));
  }
  if (url.indexOf('h_1e_1c_100Q') != -1) {
    url = url.substring(0, url.indexOf("@" + w + "w_" + h + "h_1e_1c_100Q"));
  }
  if (isNull(url)) {
    return "";
  }
  h = Math.round(h);
  w = Math.round(w);
  if (url.substring(0, 11) == "http://cdnx") {
    return url + "?x-oss-process=image/resize,m_fill,w_" + w + ",h_" + h + "/quality,q_90";
  } else if (url.substring(0, 10) == "http://cdn") {
    return url + "@" + w + "w_" + h + "h_1e_1c_100Q";
  } else {
    return url;
  }
}

const proxyImage = (host, url) => {
  return host + "/zxing/proxyImage?url=" + encodeURIComponent(url);

}

const thumbnail_cover = (url, w) => {
  if (isNull(url)) {
    return "";
  }
  if (url.indexOf('?x-oss-') != -1) {
    url = url.substring(0, url.indexOf('?x-oss-'));
  }
  if (url.indexOf('h_1e_1c_100Q') != -1) {
    url = url.substring(0, url.indexOf('@' + w + 'w_1e_1c_100Q'));
  }
  if (w > 1080) {
    w = 1080
  }
  w = Math.round(w);
  if (url.substring(0, 11) == 'http://cdnx') {
    return url + '?x-oss-process=image/resize,w_' + w + '/quality,q_90';
  } else
  if (url.substring(0, 10) == 'http://cdn') {
    return url + '@' + w + 'w_1e_1c_100Q';
  } else {
    return url;
  }
}
const token = (data) => {
  console.log(data)
  if (data == null) {
    console.log(data)
    wx.navigateTo({
      url: '/pages/login/index',
    })
    return
  }
}

// **
//  * 判断空值，包括{ } 和[]，空为true，否则为false
//   * /
const isNull = function (value) {
  if (value == null || value == undefined) return true
  if (isString(value)) {
    if (value.trim().length == 0) return true
  } else if (isArray(value)) {
    if (value.length == 0) return true
  } else if (isObject(value)) {
    for (let name in value) return false
    return true
  }
  return false;
}
/**
 * 判断是否为字符串类型，是为true，否则为false
 */
const isString = function (value) {
  return value != null && value != undefined && value.constructor == String
}
/**
 * 判断是否为数字类型，是为true，否则为false
 */
const isNumber = function (value) {
  return value != null && value != undefined && value.constructor == Number
}
/**
 * 判断是否为布尔类型，是为true，否则为false
 */
const isBoolean = function (value) {
  return value != null && value != undefined && value.constructor == Boolean
}
/**
 * 判断是否为数组类型，是为true，否则为false
 */
const isArray = function (value) {
  return value != null && value != undefined && value.constructor == Array
}
/**
 * 判断是否为对象类型，是为true，否则为false
 */
const isObject = function (value) {
  return value != null && value != undefined && value.constructor == Object
}
/**
 * 判断是否为方法类型，是为true，否则为false
 */
const isFunction = function (value) {
  return value != null && value != undefined && value.constructor == Function
}

const forwarding = function (value, token) {
  console.log(value)
  var app = getApp();
  console.log(token)
  if (!isNull(value.xuid)) {
    app.globalData.xuid = value.xuid;
    console.log('查看是否有xuid2')
    console.log(app.globalData.xuid)
    if (token == null) {
      wx.navigateTo({
        url: '/pages/login/index?cardType=true'
      })
    } else {
      lockSysUserClick(app.globalData.xuid)
    }
  }
}

const lockSysUserClick = function (xuid) {
  var app = getApp();
  lockSysUser({
    mchId: app.globalData.mchId,
    xuid: xuid,
    shopId: app.globalData.shopId
  }).then(res => {
    console.log(res)
  })
}

/**
 * 点赞
 * @param {文章id} id
 * @param {当前的this对象} _this 给定后可在执行前后添加favour字段，表示点赞
 */
const articleLaud = function (id, _this = null) {
  var app = getApp();
  _this && _this.setData({
    favour: true
  })
  return new Promise((resolve, reject) => {
    articleLaudSave({
      articleId: id,
      // status:status,
      avatar: app.globalData.userInfo.avatar
    }).then(res => {
      if (res.type == "success") {
        resolve(res)
      } else {
        _this && _this.setData({
          favour: false
        })
        reject(res)
      }
    })
  })
}

/**
 * 收藏 TODO
 * @param {文章id} id
 * @param {当前的this对象} _this 给定后可在执行前后添加favour字段，表示点赞
 */
const scenicFavorites = function (id, action = "save", _this = null) {
  var app = getApp();
  return new Promise((resolve, reject) => {
    let requestAction = null
    let favour = null
    switch (action) {
      case "save":
        favour = false
        // _this && _this.setData({ favour: !favour })
        requestAction = scenicFavoritesSave({
          scenicSpotId: id
        })
        break;
      case "del":
        favour = true
        // _this && _this.setData({ favour: !favour })
        requestAction = scenicFavoritesDel(id)
        break;
      case "list":
        requestAction = scenicFavoritesList()
        break;
      default:
        console.warn("error action!")
        return false
    }
    requestAction && requestAction.then(res => {
      if (res.type == "success") {
        resolve(res)
        _this && _this.setData({
          favour: !favour
        })
      } else {
        _this && _this.setData({
          favour: favour
        })
        reject(res)
      }
    })
  })
}


module.exports = {
  datetimeFormat: datetimeFormat,
  datetime: datetime,
  filterTime: filterTime,
  getDateFromNow: getDateFromNow,
  rateConverter: rateConverter,
  escape2Html:escape2Html,
  getUUID: getUUID,
  isNull: isNull,
  isString: isString,
  isArray: isArray,
  isNumber: isNumber,
  isBoolean: isBoolean,
  isObject: isObject,
  getUrlParameter: getUrlParameter,
  thumbnail: thumbnail,
  thumbnail_cover: thumbnail_cover,
  token: token,
  proxyImage: proxyImage,
  forwarding: forwarding,
  lockSysUserClick: lockSysUserClick,
  articleLaud: articleLaud,
  scenicFavorites: scenicFavorites
}